<template>
  <div class="my-videos-container">
    <div class="page-header">
      <h2>我的视频</h2>
      <el-button type="primary" @click="$router.push('/upload')">
        <el-icon><Plus /></el-icon>上传新视频
      </el-button>
    </div>

    <el-tabs v-model="activeTab" class="video-tabs">
      <el-tab-pane label="已发布" name="published">
        <div class="video-list" v-loading="loading">
          <div v-if="publishedVideos.length === 0 && !loading" class="empty-state">
            <el-empty description="暂无已发布的视频" />
          </div>
          <div v-else class="video-grid">
            <div v-for="video in publishedVideos" :key="video._id" class="video-item">
              <div class="video-card">
                <div class="thumbnail" @click="goToVideo(video._id)">
                  <img 
                    class="lazy-image" 
                    :data-src="backendUrl + video.thumbnail" 
                    :alt="video.title" 
                    src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 9'%3E%3C/svg%3E"
                  >
                  <span class="duration">{{ formatDuration(video.duration) }}</span>
                </div>
                <div class="video-info">
                  <h3 class="title" @click="goToVideo(video._id)">{{ video.title }}</h3>
                  <div class="stats">
                    <span>{{ formatViews(video.views) }}次观看</span>
                    <span>{{ formatDate(video.createdAt) }}</span>
                  </div>
                  <div class="actions">
                    <el-button-group>
                      <el-button size="small" @click="editVideo(video)">
                        <el-icon><Edit /></el-icon>编辑
                      </el-button>
                      <el-button size="small" type="danger" @click="confirmDelete(video)">
                        <el-icon><Delete /></el-icon>删除
                      </el-button>
                    </el-button-group>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div v-if="pagination.published.hasMore" class="load-more">
            <el-button :loading="loadingMore" @click="loadMore('published')" type="primary" plain>
              加载更多
            </el-button>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="草稿" name="draft">
        <div class="video-list" v-loading="loading">
          <div v-if="draftVideos.length === 0 && !loading" class="empty-state">
            <el-empty description="暂无草稿视频" />
          </div>
          <div v-else class="video-grid">
            <div v-for="video in draftVideos" :key="video.id" class="video-item">
              <div class="video-card">
                <div class="thumbnail">
                  <img 
                    class="lazy-image" 
                    :data-src="backendUrl + video.thumbnail" 
                    :alt="video.title" 
                    src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 9'%3E%3C/svg%3E"
                  >
                  <span class="draft-badge">草稿</span>
                </div>
                <div class="video-info">
                  <h3 class="title">{{ video.title }}</h3>
                  <div class="stats">
                    <span>{{ formatDate(video.updatedAt) }} 更新</span>
                  </div>
                  <div class="actions">
                    <el-button-group>
                      <el-button size="small" type="primary" @click="continueEdit(video)">
                        继续编辑
                      </el-button>
                      <el-button size="small" type="danger" @click="confirmDelete(video)">
                        删除
                      </el-button>
                    </el-button-group>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div v-if="pagination.draft.hasMore" class="load-more">
            <el-button :loading="loadingMore" @click="loadMore('draft')" type="primary" plain>
              加载更多
            </el-button>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 编辑视频对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑视频"
      width="600px"
    >
      <el-form
        ref="editForm"
        :model="editingVideo"
        :rules="videoRules"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="editingVideo.title" maxlength="100" show-word-limit />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="editingVideo.description"
            type="textarea"
            :rows="4"
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="分类" prop="category">
          <el-select v-model="editingVideo.category" placeholder="选择分类">
            <el-option
              v-for="item in categories"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="标签" prop="tags">
          <el-select
            v-model="editingVideo.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="输入标签"
          >
            <el-option
              v-for="tag in commonTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="隐私设置" prop="privacy">
          <el-radio-group v-model="editingVideo.privacy">
            <el-radio label="public">公开</el-radio>
            <el-radio label="unlisted">不公开</el-radio>
            <el-radio label="private">私密</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveVideoEdit" :loading="saving">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watch, nextTick, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex' // 添加 useStore 导入
import axios from '@/services/axios' // Use configured axios instance
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { formatDuration, formatViews, formatDate } from '@/utils/formatters' // Import formatters

// 定义后端服务器地址 (从环境变量读取)
const backendUrl = import.meta.env.VITE_BACKEND_URL || 'http://localhost:3000'; // 提供一个默认值以防万一

const router = useRouter()
const store = useStore() // Get store instance
const userId = computed(() => store.getters['auth/userId']) // Get userId from store

// 使用防抖函数优化滚动事件处理
const debounce = (fn, delay) => {
  let timer = null;
  return function() {
    const context = this;
    const args = arguments;
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(context, args);
    }, delay);
  };
};

// 当前激活的标签页
const activeTab = ref('published')

// 视频列表数据
const publishedVideos = ref([])
const draftVideos = ref([])

// 加载状态
const loading = ref(false)
const loadingMore = ref(false)
const saving = ref(false)

// 分页信息
const pagination = reactive({
  published: {
    page: 1,
    pageSize: 12,
    hasMore: true
  },
  draft: {
    page: 1,
    pageSize: 12,
    hasMore: true
  }
})

// 编辑对话框
const editDialogVisible = ref(false)
const editingVideo = ref(null)
const editForm = ref(null)

// 表单验证规则
const videoRules = {
  title: [
    { required: true, message: '请输入视频标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入视频描述', trigger: 'blur' },
    { max: 2000, message: '描述不能超过 2000 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择视频分类', trigger: 'change' }
  ],
  privacy: [
    { required: true, message: '请选择隐私设置', trigger: 'change' }
  ]
}

// 常用标签
const commonTags = [
  '教程', '搞笑', '音乐', '游戏', '科技', '编程', '旅行', '美食', '健身', '时尚',
  '电影', '动画', '体育', '新闻', '知识', '汽车', '宠物', '手工', '摄影', '绘画'
]

// 分类选项
const categories = [
  { value: 'entertainment', label: '娱乐' },
  { value: 'music', label: '音乐' },
  { value: 'games', label: '游戏' },
  { value: 'education', label: '教育' },
  { value: 'tech', label: '科技' },
  { value: 'life', label: '生活' }
]

// 获取视频列表
const fetchVideos = async (status = 'published', reset = true) => {
  // 增加 userId 检查
  if (!userId.value) {
    console.warn('User ID not available yet, skipping fetchVideos.');
    // 可以选择显示加载状态或提示信息
    if (reset) loading.value = false;
    if (!reset) loadingMore.value = false;
    return; 
  }

  if (reset) {
    loading.value = true;
    if (status === 'published') {
      publishedVideos.value = [];
      pagination.published.page = 1;
      pagination.published.hasMore = true;
    } else {
      draftVideos.value = [];
      pagination.draft.page = 1;
      pagination.draft.hasMore = true;
    }
  } else {
    if (!pagination[status].hasMore) return;
    loadingMore.value = true;
  }

  try {
    const params = {
      status: status,
      page: pagination[status].page,
      limit: pagination[status].pageSize, // 使用 pageSize
      sort: 'createdAt_desc' // Or other sorting options
    };

    // Use the correct API endpoint for user's videos, including userId
    const response = await axios.get(`/api/user/${userId.value}/videos`, { params });
    const newVideos = response.data.videos || [];
    // 假设后端直接返回 hasMore 标志，或者根据返回的视频数量判断
    const hasMore = newVideos.length === pagination[status].pageSize;

    // 添加日志：打印第一个视频的缩略图路径
    if (newVideos.length > 0) {
      console.log(`[fetchVideos] 第一个视频缩略图路径: ${newVideos[0].thumbnail}`);
    }

    if (status === 'published') {
      if (reset) {
        publishedVideos.value = newVideos;
      } else {
        publishedVideos.value.push(...newVideos);
      }
      pagination.published.hasMore = hasMore;
      if (hasMore) {
        pagination.published.page++;
      }
    } else {
      if (reset) {
        draftVideos.value = newVideos;
      } else {
        draftVideos.value.push(...newVideos);
      }
      pagination.draft.hasMore = hasMore;
      if (hasMore) {
        pagination.draft.page++;
      }
    }

  } catch (error) {
    console.error(`获取${status === 'published' ? '已发布' : '草稿'}视频失败:`, error);
    ElMessage.error(error.response?.data?.error || `获取${status === 'published' ? '已发布' : '草稿'}视频失败`);
    if (reset) {
        pagination[status].hasMore = false; // Stop loading more on error
    }
  } finally {
    if (reset) {
      loading.value = false;
    } else {
      loadingMore.value = false;
    }
    // 确保在 finally 中调用 lazyLoadImages
    nextTick(lazyLoadImages);
  }
};

// 加载更多
const loadMore = (status) => {
  fetchVideos(status, false);
};

// 编辑视频
const editVideo = (video) => {
  editingVideo.value = { ...video }
  editDialogVisible.value = true
}

// 保存编辑
const saveVideoEdit = async () => {
  editForm.value.validate(async (valid) => {
    if (valid) {
      saving.value = true;
      try {
        const videoId = editingVideo.value._id; // Use _id
        // Use PATCH for partial updates
        const response = await axios.patch(`/api/videos/${videoId}`, editingVideo.value);
        ElMessage.success('视频信息更新成功');
        editDialogVisible.value = false;
        // Update the video in the local list
        const listToUpdate = editingVideo.value.status === 'published' ? publishedVideos : draftVideos;
        const index = listToUpdate.value.findIndex(v => v._id === videoId);
        if (index !== -1) {
          listToUpdate.value[index] = { ...listToUpdate.value[index], ...response.data.video };
        }
      } catch (error) {
        console.error('保存视频编辑失败:', error);
        ElMessage.error(error.response?.data?.error || '保存失败');
      } finally {
        saving.value = false;
      }
    } else {
      console.log('表单验证失败');
      return false;
    }
  });
};

// 确认删除视频
const confirmDelete = (video) => {
  ElMessageBox.confirm(
    '确定要删除这个视频吗？此操作不可恢复。',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteVideo(video)
  }).catch(() => {})
}

const deleteVideo = async (video) => {
  try {
    await axios.delete(`/api/videos/${video._id}`) // Use _id instead of id
    ElMessage.success('视频删除成功')
    
    // 刷新视频列表
    fetchVideos(activeTab.value, true)
  } catch (error) {
    console.error('删除视频失败:', error)
    ElMessage.error('删除视频失败')
  }
}

// Remove local formatters as they are imported
// const formatDuration = (seconds) => { ... }
// const formatViews = (views) => { ... }
// const formatDate = (date) => { ... }

// 跳转到视频详情页
const goToVideo = (videoId) => {
  router.push(`/video/${videoId}`)
}

// 监听标签页切换
watch(activeTab, (newTab) => {
  fetchVideos(newTab, true)
})

// 组件挂载时获取数据
onMounted(() => {
  fetchVideos(activeTab.value, true)
})

// 懒加载图片函数
const lazyLoadImages = () => {
  console.log('[lazyLoadImages] 开始执行懒加载检查'); // 添加日志
  // 使用 nextTick 确保 DOM 已更新
  nextTick(() => {
    // 获取所有带有 lazy-load 类的图片
    const lazyImages = document.querySelectorAll('.lazy-image');
    console.log(`[lazyLoadImages] 找到 ${lazyImages.length} 个需要懒加载的图片`); // 添加日志
    if (lazyImages.length === 0) return;

    // 遍历并处理每个图片
    lazyImages.forEach(img => {
      // 检查图片是否在视口中
      if (isInViewport(img) && img.dataset.src) {
        console.log(`[lazyLoadImages] 图片进入视口，加载: ${img.dataset.src}`); // 添加日志
        // 设置 src 属性并移除 lazy-load 类
        img.src = img.dataset.src;
        img.classList.remove('lazy-load');
      }
    });
  });
};

// 检查元素是否在视口中
const isInViewport = (element) => {
const rect = element.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
};
</script>

<style scoped>
.my-videos-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.video-tabs {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
}

.video-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.video-card {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  transition: transform 0.2s;
}

.video-card:hover {
  transform: translateY(-5px);
}

.thumbnail {
  position: relative;
  width: 100%;
  padding-top: 56.25%; /* 16:9 宽高比 */
  overflow: hidden;
  cursor: pointer;
}

.thumbnail img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.duration {
  position: absolute;
  bottom: 8px;
  right: 8px;
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 2px 4px;
  border-radius: 4px;
  font-size: 12px;
}

.draft-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  background-color: #E6A23C;
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.video-info {
  padding: 12px;
}

.title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  cursor: pointer;
}

.stats {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.actions {
  display: flex;
  justify-content: flex-end;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.load-more {
  text-align: center;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .my-videos-container {
    padding: 10px;
  }

  .video-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 10px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>
